# -*- coding: utf-8 -*-
# @Time : 2020/11/01 11:30
# @Author : Houor
# @Site : https://my.oschina.net/houor
# @File : quadratic_interpolation.py
# @Description: 二次插值法

def func(x):
    return 3 * (x ** 3) - 4 * x + 2


def inter_point(x1, x2, x3):
    f1 = func(x1)
    f2 = func(x2)
    f3 = func(x3)

    c1 = (f1 - f3) / (x1 - x3)
    c2 = ((f1 - f2) / (x1 - x2) - c1) / (x2 - x3)
    i_x = (x1 + x3 - (c1 / c2)) / 2.0

    return f1, f2, f3, func(i_x), i_x, c1, c2


flag = False
idx = 1

epsilon = 0.02
a = 0
b = 3
h = 1

x1 = a
x2 = 1
x3 = b

while not flag:

    f1, f2, f3, f4, i_x, c1, c2 = inter_point(x1, x2, x3)

    print('idx = ', idx, ':')
    print('\t\ta = ', a, ', \tb = ', b)
    print('\t\tx1 = ', x1, ', \tx2 = ', x2, ', \tx3 = ', x3)
    print('\t\tf1 = ', f1, ', \tf2 = ', f2, ', \tf3 = ', f3)
    print('\t\tc1 = ', c1, ', \tc2 = ', c2)
    print('\t\tx_bar = ', i_x, '\tf_bar = ', f4)
    print('\t\t|x2 - x_bar| = ', abs(x2 - i_x))

    if abs(x2 - i_x) < epsilon:
        flag = True

    idx = idx + 1

    if i_x < x2:
        if f2 > f4:
            a = x1
            b = x2

            x1 = a
            x2 = i_x
            x3 = b
        else:
            a = i_x
            b = x3

            x1 = a
            x2 = x2
            x3 = b
    else:
        if f2 > f4:
            a = x2
            b = x3

            x1 = a
            x2 = i_x
            x3 = b
        else:
            a = x1
            b = i_x

            x1 = a
            x2 = x2
            x3 = b

print('x = ', i_x)
